package com.cd.miniprogramServer.common.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@Order(1)
//过滤器配置，在http请求进入controller之前执行，可用于拦截请求，做一下前置处理，例如验证用户权限，记录请求日志等
public class RequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("RequestFilter 初始化完成");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        // 记录请求信息
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.info("拦截到请求: {} {}", method, requestURI);
        
        // 继续执行过滤器链
        filterChain.doFilter(request, response);
        
        // 记录响应信息
        log.info("请求处理完成: {} {}, 状态码: {}", method, requestURI, response.getStatus());
    }

    @Override
    public void destroy() {
        log.info("RequestFilter 销毁完成");
    }
}